<template>
  <div class="app-container">
    <div class="backgroundBox">
      <div class="operateBox">
        <el-form
          :model="queryParams"
          ref="queryRef"
          :inline="true"
          v-show="showSearch"
        >
          <div style="display: flex;justify-content: space-between;">
            <div>
              <el-form-item
                label="班级"
                prop="deptName"
              >
                
                <el-tree-select
                  v-model="queryParams.deptId"
                  placeholder="请选择部门"
                  :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
                  :data="deptList"
                  style="width: 240px"
                  @change="handleQuery"
                >
                  <template #default="{data:{deptName}}">
                    {{ deptName }}
                  </template>
                </el-tree-select>

              </el-form-item>
              <el-form-item>

                <img
                  src="@/assets/images/reset.png"
                  style="cursor: pointer; width: 24px; height: 24px;"
                  @click="resetData"
                >
                <span
                  style="color: #363636; font-size: 14px;cursor: pointer;margin-left: 8px;"
                  @click="resetData"
                >重置数据</span>
              </el-form-item>
            </div>

            <div>
              <el-button
                class="exportBtn"
                @click="exportDeptData"
                :disabled="selectionDeptData.length === 0"
              >
                导出
              </el-button>
            </div>
          </div>
        </el-form>

      </div>

      <div class="datBox">
        <el-row
          :gutter="10"
          class="mb8"
          style="display: flex;justify-content: space-between;"
        >
          <el-col :span="1.5">
            <el-button
              plain
              class="batchDeleteBtn"
              @click="batchDelete"
              :disabled="ids.length===0"
            >批量删除</el-button>
          </el-col>

          <el-col :span="1.5">
            <el-dropdown @command="newCreateClasses">
              <el-button
                plain
                class="addClassBtn"
              >
                <el-icon class="plusIcon">
                  <Plus />
                </el-icon>
                <span>新建班级</span>
              </el-button>

              <template #dropdown>
                <el-dropdown-menu style="width: 144px;">
                  <el-dropdown-item
                    command="newCreateClass">新建班级</el-dropdown-item>
                  <el-dropdown-item command="batchNewCreateClass">
                    批量新建
                    <el-upload
                      ref="upload"
                      action=""
                      :auto-upload="false"
                      :show-file-list="false"
                      accept=".xlsx, .xls"
                      :on-change="handleFileChange"
                    ></el-upload>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-col>
        </el-row>

        <el-table
          v-if="refreshTable"
          v-loading="loading"
          :data="deptList"
          @selection-change="handleSelectionChange"
          style="margin-top: 24px;"
        >
          <el-table-column
            type="selection"
            width="200"
          />

          <el-table-column
            label="编号"
            width="100"
            align="center"
          >
            <template #default="scope">
              <!-- 生成不重复的序号 -->
              {{ (queryParams.pageNum - 1)* queryParams.pageSize + scope.$index + 1 }}
            </template>
          </el-table-column>

          <el-table-column
            prop="deptName"
            label="班级"
            width="320"
            align="center"
          ></el-table-column>
          <el-table-column
            label="创建时间"
            align="center"
            sortable
            prop="createTime"
            width="465"
          >
            <template #default="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-button
                link
                type="primary"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:dept:edit']"
              >
                <el-icon style="color: #5974ff;font-size: 16px;">
                  <EditPen />
                </el-icon>
                <span style="font-size: 12px;color: #363636;">编辑</span>
              </el-button>
              <el-button
                link
                type="primary"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:dept:remove']"
              >
                <el-icon style="color: #f99d38;font-size: 16px;">
                  <Delete />
                </el-icon>
                <span style="font-size: 12px;color: #363636;">删除</span>
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </div>

    <!-- 添加或修改部门对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="500px"
      align-center
    >
      <el-form
        ref="deptRef"
        :model="form"
        :rules="rules"
        label-width="80px"
        style="display: flex;flex-direction: column;align-items: center;"
      >
        <el-row>
          <el-col>
            <el-form-item
              label="班级名称"
              prop="deptName"
            >
              <el-input
                v-model="form.deptName"
                placeholder="请输入班级名称"
              />
            </el-form-item>
          </el-col>
          
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            @click="cancel"
            class="cancelBtn"
            plain
          ><span style="color: #5974FF;font-size: 16px;">
              取 消
            </span></el-button>
          <el-button
            type="primary"
            @click="submitForm"
            class="saveBtn"
            plain
          ><span style="color: #FFFFFF;font-size: 16px;">
              保 存
            </span></el-button>

        </div>
      </template>
    </el-dialog>
    <BatchAddDialog
      ref="batchAddDialogRef"
      @download="templateDownload"
      @batchUpload="handleFileChange"
    ></BatchAddDialog>
  </div>
</template>

<script setup name="Dept">
import { listDept, getDept, delDept, addDept, updateDept, listDeptExcludeChild } from "@/api/system/dept";

// 引入批量上传的弹窗
import BatchAddDialog from "./batchAddDialog.vue"
import { exportExcel, importExcel } from "@/utils/peak-tools.js";
import { get } from '@vueuse/core';
const { proxy } = getCurrentInstance();
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");
import { ElMessage, ElMessageBox } from 'element-plus'

const deptList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const deptOptions = ref([]);
const isExpandAll = ref(true);
const refreshTable = ref(true);

const data = reactive({
  form: {},
  queryParams: {
    deptName: undefined,
    status: undefined,
    deptId: "",
    pageNum: 1,
    pageSize: 10
  },
  rules: {
    parentId: [{ required: true, message: "上级部门不能为空", trigger: "blur" }],
    deptName: [{ required: true, message: "部门名称不能为空", trigger: "blur" }, {
      validator: (rule, value, callback) => {
        if (value.trim() === '') {
          callback(new Error('请输入非空值且不能包含空格'));
        } else if (/\s/.test(value)) {
          // 使用正则表达式检查是否有空格  
          callback(new Error('输入不能包含空格'));
        } else {
          callback();
        }
      }, trigger: "blur"
    }],
    orderNum: [{ required: true, message: "显示排序不能为空", trigger: "blur" }],
    email: [{ type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }],
    phone: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }]
  },
});

const { queryParams, form, rules } = toRefs(data);

const total = ref(0)

/** 查询部门列表 */
function getList () {
  loading.value = true;
  listDept(queryParams.value).then(response => {
    deptList.value = response.rows
    total.value = response.total
    loading.value = false;
  });
}
/** 取消按钮 */
function cancel () {
  open.value = false;
  reset();
}
/** 表单重置 */
function reset () {
  form.value = {
    deptId: undefined,
  };
  proxy.resetForm("deptRef");
}
/** 搜索按钮操作 */
function handleQuery () {
  getList();
}
/** 重置按钮操作 */
function resetQuery () {
  proxy.resetForm("queryRef");
  form.value = {
    deptId: undefined,
  };
  selectDept.value = ""
  handleQuery();
}
/** 新增按钮操作 */
function handleAdd (row) {
  reset();
  listDept().then(response => {
    deptOptions.value = response.data
  });
  if (row != undefined) {
    form.value.parentId = row.deptId;
  }
  open.value = true;
  title.value = "添加班级";
}
/** 展开/折叠操作 */
function toggleExpandAll () {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}
/** 修改按钮操作 */
function handleUpdate (row) {
  reset();
  listDeptExcludeChild(row.deptId).then(response => {
    deptOptions.value = response.data
  });
  getDept(row.deptId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改班级";
  });
}
/** 提交按钮 */
function submitForm () {
  proxy.$refs["deptRef"].validate(valid => {
    if (valid) {
      if (form.value.deptId != undefined) {
        updateDept(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDept([form.value]).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 删除按钮操作 */
function handleDelete (row) {
  // proxy.$modal.confirm('是否确认删除名称为"' + row.deptName + '"的数据项?').then(function () {
  //   return delDept(row.deptId);
  // }).then(() => {
  //   getList();
  //   proxy.$modal.msgSuccess("删除成功");
  // }).catch(() => { });

  ElMessageBox.confirm('是否确认删除名称为"' + row.deptName + '"的数据项?', '系统提示', {
    type: 'warning',
    confirmButtonClass: 'confirmDeleteBtn',
    cancelButtonClass: 'cancelDeleteBtn'
  }).then(function () {
    return delDept(row.deptId);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { })

}

getList();

// 重置数据方法
function resetData () {
  queryParams.value = {
    deptName: undefined,
    status: undefined,
    deptId: "",
    pageNum: 1,
    pageSize: 10
  }
  handleQuery()
}

// 接收选中的ids
const ids = ref([])
const selectionDeptData = ref([])

// 处理复选框选中的方法
function handleSelectionChange (selection) {
  selectionDeptData.value = selection
  ids.value = selection.map(item => item.deptId)
}

// 批量删除的方法
async function batchDelete () {
  let idString = ids.value.join(',')


  ElMessageBox.confirm(
    `您确定要删除编号为${idString}的班级吗？`,
    '系统提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const res = await delDept(ids.value)
      getList()
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

// 导出班级数据的方法
async function exportDeptData () {
  let list = JSON.parse(JSON.stringify(selectionDeptData.value))
  let tableTemplateHead = {
    班级: "deptName",
  }
  const res = await exportExcel("部门信息.xlsx", tableTemplateHead, list, (sheet) => {
    let columnWidth = [14, 16, 25, 10, 14, 30, 30, 30, 10];
    sheet["!cols"] = columnWidth.map((wch) => ({
      wch,
    }));
    return sheet;
  })
}

// 下载模板的方法
async function templateDownload () {
  const res = await exportExcel(
    "班级管理导入模板.xlsx",
    {
      班级: "deptName"
    },
    [{
      deptName: "一班"
    }],
    (sheet) => {
      let columnWidth = [16, 10, 10, 32, 16, 10, 30, 30, 30, 10];
      sheet["!cols"] = columnWidth.map((width) => ({
        width,
      }));
      return sheet;
    }
  )
}

const batchAddDialogRef = ref(null)

// 上传下拉菜单方法
function newCreateClasses (command) {
  if (command === "newCreateClass") {
    handleAdd()
  } else if (command === "batchNewCreateClass") {
    batchAddDialogRef.value.dialogVisible = true
  }
}

const uploadClassesFile = ref(null)
// 批量上传
async function handleFileChange (file) {
  try {
    uploadClassesFile.value = file
    let tableTemplateHead = {
      班级: "deptName"
    }
    const res = await importExcel(file.raw, tableTemplateHead)


    if (Array.isArray(res.data)) {
      for (let i = 0; i < res.data.length; i++) {
        if (res.data[i].hasOwnProperty("undefined")) {
          return ElMessage({
            type: "error",
            message: `第${i + 1}个数据有误`
          })
        } else if (!res.data[i].hasOwnProperty("deptName")) {
          return ElMessage({
            type: "error",
            message: `第${i + 1}个数据班级名称不能为空`
          })
        }
      }
      const res2 = await addDept(res.data)
      getList()
      uploadClassesFile.value = null
      proxy.$modal.msgSuccess("导入成功")
    } else {
      return ElMessage({
        type: 'error',
        message: res.msg,
      })
    }
  } catch (error) {

  }
}


</script>

<style scoped lang="scss">
.app-container {
  padding: 32px;
}
.backgroundBox {
  background-color: #fff;

  border-radius: 10px;

  .operateBox {
    height: 88px;
    padding: 24px 32px;
    border-bottom: 1px solid #d4d4d4;

    .exportBtn {
      width: 80px;
      height: 40px;
      border: 1px solid #5974ff;
      font-size: 16px;
      color: #5974ff;

      &:hover {
        background-color: transparent;
      }

      &:focus {
        background-color: transparent;
      }
    }
  }
  .datBox {
    min-height: 936px;
    padding: 24px 32px 0 32px;

    .templateDownloadBtn {
      font-size: 16px;
      margin-right: 48px;
      color: #44bd60;
    }

    .batchDeleteBtn {
      width: 112px;
      height: 40px;
      border: 1px solid #5974ff;
      font-size: 16px;
      color: #5974ff;
    }

    ::v-deep(.el-table__header) {
      height: 56px;
    }

    ::v-deep(.el-table__row) {
      height: 56px;
    }

    .addClassBtn {
      width: 144px;
      height: 40px;
      background: #5974ff;
      font-size: 16px;
      color: #ffffff;
      border-radius: 6px;

      .plusIcon {
        margin-right: 12px;
      }
    }
  }
}

.saveBtn {
  width: 108px;
  height: 40px;
  border: 1px solid #5974ff;
  background: #5974ff;
  border-radius: 6px 6px 6px 6px;
}

.cancelBtn {
  width: 108px;
  height: 40px;
  border: 1px solid #5974ff;
  border-radius: 6px 6px 6px 6px;
}

// 模态框居中显示
::v-deep(.el-dialog:not(.is-fullscreen)) {
  margin: auto !important;
}
</style>
